package com.wgj.android.dialog;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatDialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.jiaai.xui.adapter.XRecyclerViewAdapter;
import com.jiaai.xui.adapter.decoration.DividerDecoration;
import com.jiaai.xui.utils.XDensityUtils;
import com.wgj.android.R;
import com.wgj.android.adapter.BaiDuAddressAdapter;
import com.wgj.android.entity.Address;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/5/23.
 */

public class BaiDuSearchDialog extends AppCompatDialogFragment implements OnGetSuggestionResultListener, OnGetGeoCoderResultListener {
    private GeoCoder mSearch;
    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    private SuggestionSearch mSuggestionSearch = null;
    private Dialog dialog;
    @BindView(R.id.ib_black)
    ImageButton ibBlack;
    @BindView(R.id.searchkey)
    EditText searchkey;
    @BindView(R.id.cancel)
    ImageButton cancel;
    private List<SuggestionResult.SuggestionInfo> infos=new ArrayList<>();
    private List<Address> addresses=new ArrayList<>();
    private BaiDuAddressAdapter adapter;
    private View view;

    private OnSelectAddCallback callback;
    private int sign=0;

    private int size=0;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_baidu_search, null, false);
        ButterKnife.bind(this, view);
        initView();
    }

    private void initView() {
        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);

        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(this);
       // adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line);
        adapter=new BaiDuAddressAdapter(recycleView,addresses);
        recycleView.setHasFixedSize(true);
        recycleView.addItemDecoration(new DividerDecoration(Color.GRAY, XDensityUtils.dp2px(1f)));
        recycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycleView.setAdapter(adapter);
        searchkey.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable arg0) {
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                if (cs.length() <= 0) {
                    adapter.clear();
                    return;
                }
                mSuggestionSearch.requestSuggestion((new SuggestionSearchOption()).keyword(cs.toString()).city(" "));
                //mSuggestionSearch.requestSuggestion((new SuggestionSearchOption()).keyword("常平"));
            }
        });
        adapter.setOnItemClickListener(new XRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {

                callback.onSelect(addresses.get(i));
                dismiss();
            }
        });

    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        super.onCreateDialog(savedInstanceState);
        if (dialog == null) {
            // 使用不带Theme的构造器, 获得的dialog边框距离屏幕仍有几毫米的缝隙。
            initDialogStyle(view);
        }
        return dialog;
    }

    private void initDialogStyle(View view) {
        dialog = new Dialog(getActivity(), R.style.dialog_setting);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false); // 外部点击取消
        // 设置宽度为屏宽, 靠近屏幕底部。
        Window window = dialog.getWindow();
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); //显示软键盘
        window.setWindowAnimations(R.style.popupwindow_anim_style);
        WindowManager.LayoutParams lp = window.getAttributes();
        //lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(lp);
    }

    @OnClick({R.id.cancel,R.id.ib_black})
    public void onCancel(View v) {
        switch (v.getId()){
            case R.id.cancel:
                searchkey.getText().clear();
                break;
            case R.id.ib_black:
                dismiss();
                break;
        }

    }

    @Override
    public void onGetSuggestionResult(SuggestionResult suggestionResult) {
        if (suggestionResult == null || suggestionResult.getAllSuggestions() == null) {
            return;
        }
        //adapter.clear();
       // infos.clear();
        //infos.addAll(suggestionResult.getAllSuggestions());
        //adapter.notifyDataSetChanged();
        addresses.clear();
        size=suggestionResult.getAllSuggestions().size();
          for (SuggestionResult.SuggestionInfo info : suggestionResult.getAllSuggestions()) {
            if (info.key != null&&info.pt!=null){
                //adapter.add(info.key);
                //infos.add(info);
                mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                        .location(info.pt).newVersion(1));
            }else {
                size-=size-1;
            }

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mSearch.destroy();
        dismiss();
        dialog=null;
        mSuggestionSearch.destroy();
    }

    public BaiDuSearchDialog setAddCallback(OnSelectAddCallback callback) {
        this.callback = callback;
        return this;
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

            if(reverseGeoCodeResult!=null&&reverseGeoCodeResult.getPoiList().size()>0){
                sign+=1;
                PoiInfo points =reverseGeoCodeResult.getPoiList().get(0);
                Address address = new Address();
                address.setLatLng(points.location);
                address.setName(points.name);
                address.setAddress(points.address);
                addresses.add(address);
                if(sign==size){
                    adapter.notifyDataSetChanged();
                    sign=0;
                }
            }

    }

    public  interface  OnSelectAddCallback{
        public  void  onSelect(Address address);
    }
}
